/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2025-10-09
 * Time: 15:06
 */
class MyBlockingQueue{
    private String[] data = null;

    private int head = 0;

    private int tail = 0;

    private int size = 0;


    public MyBlockingQueue(int capcity){
        data = new String[capcity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized(this){
            while(size >= data.length){
                this.wait();
            }
            data[tail] = elem;
            tail++;
            //这步是干嘛的：数组复位，复用了数组索引0的空间
            if(tail >= data.length){
                tail = 0;
            }

            size++;
            //是如何唤醒的？
            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized(this){
            while(size == 0){
                this.wait();
            }
            String ret = data[head];
            head++;
            //这步是干嘛的？
            if(head >= data.length){
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}


public class demo1 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);

        Thread producer = new Thread(() -> {
            int n = 0;
            while(true){
                try {
                    queue.put(n + " ");
                    System.out.println("生产元素：" + n);
                    n++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread consumer = new Thread(() ->{
            while(true){
                String n = null;
                try {
                    n = queue.take();
                    System.out.println("消费元素：" + n);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        producer.start();
        consumer.start();
    }
}
